include RbCommonHelper

class RbTasksController < RbApplicationController
  unloadable

  def create
    @task  = Task.create_with_relationships(params, User.current.id, @project.id)
    result = @task.errors.length
    status = (result == 0 ? 200 : 400)
    @include_meta = true
    
    respond_to do |format|
      format.html { render :partial => "task", :object => @task, :status => status }
    end
  end

  def update

    # logging hours
    if(RbTasksController.isNumeric(params[:log_hours]))
      
      # subtract from remaining hours
      if(RbTasksController.isNumeric(params[:remaining_hours]))
	remaining = Float(params[:remaining_hours]) - Float(params[:log_hours])
	if(remaining<0)
	  remaining = 0
	end
        params[:remaining_hours] = remaining
      end
	  
      # add time log entry
      time_entry = TimeEntry.new(:project => @project, :issue => Issue.find_by_id(params[:id]), :user => User.current,
                                 :spent_on => User.current.today, 'hours' => params[:log_hours], 'activity_id' => -1, 'comments' => '')
      time_entry.save
    end
    
    @task = Task.find_by_id(params[:id])
    result = @task.update_with_relationships(params)
    status = (result ? 200 : 400)
    @include_meta = true
    
    respond_to do |format|
      format.html { render :partial => "task", :object => @task, :status => status }
    end
  end

  def self.isNumeric(s)
    Float(s) != nil rescue false
  end  
  
end
